import { Fields, TableAction } from "@/types/public";
import { Button, Popconfirm, Space, Select, Tag } from "antd";
import React from "react";
import {
  EditOutlined,
  DeleteOutlined,
  FolderAddOutlined,
  UnorderedListOutlined,
  AreaChartOutlined,
} from "@ant-design/icons";
import { getOptionValueFromTable } from "@/common/common";
import { tagsStatusEmun } from "../public/fields";
export const PrimaryKey = "deviceId";
const statusOptions = [
  {
    title: "未激活",
    value: 0,
  },
  {
    title: "在线",
    value: 1,
  },
  {
    title: "离线",
    value: 2,
  },
  {
    title: "故障",
    value: 3,
  },
];

// 设备信息数据结构定义
export interface DeviceInfoFeild {
  /** 设备唯一标识符 (符合UUID标准) */
  deviceId: number;

  projectId: Number;

  /** 分组ID */
  groupId: number;

  /** 协议ID */
  protocolId: number;

  /** 模板ID */
  templateId: number;

  /** 关联的产品型号代码 (SN) */
  deviceSn: string;

  /** 设备可读名称 (用户自定义) */
  deviceName: string;

  /** 设备加密密钥 (SHA-256哈希存储) */
  deviceSecret: string;

  /** 设备状态: 0-未激活,1-在线,2-离线,3-故障 */
  status: number;

  /** 最后活动时间 (带时区时间戳) */
  lastActive: string | Date;

  /** 最近连接的IP地址 */
  ipAddress: string;

  /** 设备GPS坐标 (WGS84地理坐标系) */
  location: any;

  /** 设备标签集合 (扩展属性如{"region":"east","priority"}) */
  tags: any;

  /** 设备元数据 (厂商自定义属性存储) */
  metadata: any;

  /** 排序 */
  sort: number;

  /** 创建时间 */
  createdAt: string | Date;

  /** 更新时间 */
  updatedAt: string | Date;
  /**关联设备 */
  linkedDevice: number;
  //从设备地址
  slaveAddress: number;
}
export const createDeviceInfoFeildField = async (
  tableAction: TableAction<DeviceInfoFeild> = {}

  // groupOptions: any[] = await getOptionValueFromTable("/device/group/list", {}, ["group_id", "group_name"]))
  // protocolOptions: any[] = [],
  // templateOptions: any[] = []
): Promise<Fields[]> => {
  const groupOptions = await getOptionValueFromTable("device_group", {}, [
    "groupId",
    "groupName",
  ]);
  const projectOptions = await getOptionValueFromTable("projects", {}, [
    "projectId",
    "projectName",
  ]);
  const linkedDeviceOptions = await getOptionValueFromTable(
    "device",
    {
      slaveAddress: 0,
    },
    ["deviceId", "deviceName"]
  );

  const protocolOptions: any[] = await getOptionValueFromTable(
    "protocol_management",
    {},
    ["id", "protocolName"]
  );

  const templateOptions: any[] = await getOptionValueFromTable("template", {}, [
    "id",
    "name",
  ]);

  return [
    {
      valueType: "number",
      inputType: "input",
      key: "deviceId",
      title: "设备ID",
      dataIndex: "deviceId",
      placeholder: "设备唯一标识符 (符合UUID标准)",
      disabled: true,
      width: 80,
      isEdit: false,
    },

    {
      valueType: "number",
      inputType: "select",
      key: "projectId",
      title: "项目ID",
      dataIndex: "projectId",
      options: projectOptions,
      placeholder: "请选择项目ID",
      width: 80,
      isEdit: true,
    },
    {
      valueType: "string",
      inputType: "input",
      title: "设备名称",
      dataIndex: "deviceName",
      width: 180,
      key: "deviceName",
      placeholder: "请输入设备名称",
      rules: [
        { required: false },
        { max: 255, message: "设备名称长度不能超过255字符" },
      ],
    },

    {
      valueType: "number",
      inputType: "select",
      title: "关联DUT",
      dataIndex: "linkedDevice",
      width: 180,
      key: "linkedDevice",
      placeholder: "请选择主设备DUT",
      options: linkedDeviceOptions,
      rules: [{ required: false }],
      render(v, record) {
        let name = linkedDeviceOptions.find((v1: any) => v1.value == v)?.label;
        return <Tag color="success">{name || "-"}</Tag>;
      },
    },
    {
      valueType: "number",
      inputType: "input",
      key: "slaveAddress",
      title: "从设备地址",
      visible: true,
      isEdit: false,
      width: 180,
      dataIndex: "slaveAddress",
      placeholder: "请输入从设备地址（如Modbus从站ID）",
      rules: [{ required: true, message: "从设备地址不能为空" }],
      tooltip: '从设备地址（对应UI界面"从设备地址"输入框）',
    },
    {
      valueType: "number",
      inputType: "select",
      title: "分组",
      dataIndex: "groupId",
      key: "groupId",
      placeholder: "请选择分组",
      options: groupOptions,
      visible: false,
      rules: [{ required: false }],
    },
    {
      valueType: "number",
      inputType: "select",
      title: "协议",
      visible: false,
      dataIndex: "protocolId",
      key: "protocolId",
      placeholder: "请选择协议",
      options: protocolOptions,
      rules: [{ required: false }],
    },
    {
      valueType: "number",
      inputType: "select",
      title: "模板",
      dataIndex: "templateId",
      key: "templateId",
      visible: false,
      placeholder: "请选择模板",
      options: templateOptions,
      rules: [{ required: false }],
    },
    {
      valueType: "string",
      inputType: "input",
      title: "设备SN",
      dataIndex: "deviceSn",
      width: 180,

      key: "deviceSn",
      placeholder: "请输入设备序列号",
      rules: [
        { required: false },
        { max: 128, message: "设备SN长度不能超过128字符" },
      ],
    },

    {
      valueType: "string",
      inputType: "password",
      title: "设备密钥",
      dataIndex: "deviceSecret",
      visible: false,
      key: "deviceSecret",
      placeholder: "请输入设备密钥",
      rules: [
        { required: false },
        { max: 64, message: "设备密钥长度不能超过64字符" },
        // {
        //   pattern: /^[a-f0-9]{64}$/i,
        //   message: "设备密钥必须是64位SHA-256哈希值",
        // },
      ],
    },
    {
      valueType: "number",
      inputType: "select",
      title: "设备状态",
      dataIndex: "status",
      key: "status",
      placeholder: "请选择设备状态",
      width: 90,
      options: statusOptions,
      rules: [{ required: false }],
      render: (v, record) => {
        let name = statusOptions.find((v1: any) => v1.value == v)?.title;
        return <Tag color={tagsStatusEmun[v]}>{name}</Tag>;
      },
    },
    // {
    //   valueType: "string",
    //   inputType: "date-picker",
    //   title: "最后活动时间",
    //   dataIndex: "lastActive",
    //   key: "lastActive",
    //   placeholder: "请选择最后活动时间",
    //   rules: [{ required: false }],
    // },
    {
      valueType: "string",
      inputType: "input",
      title: "IP地址",
      dataIndex: "ipAddress",
      visible: false,
      key: "ipAddress",
      placeholder: "请输入IP地址",
      // rules: [
      //   { required: false },
      //   {
      //     pattern:
      //       /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      //     message: "请输入有效的IP地址",
      //   },
      // ],
    },
    {
      valueType: "number",
      inputType: "input",
      title: "地理位置",
      dataIndex: "location",
      key: "location",
      visible: false,
      placeholder: "请选择地理位置",
      rules: [{ required: false }],
    },
    {
      valueType: "string",
      inputType: "textarea",
      title: "设备标签",
      dataIndex: "tags",
      visible: false,
      key: "tags",
      placeholder: '请输入设备标签，如{"region":"east","priority":1}',
      rules: [
        {
          validator: async (_: any, value: any) => {
            if (value) {
              try {
                JSON.parse(value);
                return Promise.resolve();
              } catch (e) {
                return Promise.reject(new Error("请输入有效的JSON格式"));
              }
            }
            return Promise.resolve();
          },
        },
      ],
    },
    {
      valueType: "string",
      inputType: "textarea",
      title: "设备元数据",
      dataIndex: "metadata",
      key: "metadata",
      placeholder: "请输入设备元数据",
      visible: false,
      rules: [
        {
          validator: async (_: any, value: any) => {
            if (value) {
              try {
                JSON.parse(value);
                return Promise.resolve();
              } catch (e) {
                return Promise.reject(new Error("请输入有效的JSON格式"));
              }
            }
            return Promise.resolve();
          },
        },
      ],
    },
    {
      valueType: "number",
      inputType: "input-number",
      title: "排序",
      dataIndex: "sort",
      key: "sort",
      placeholder: "请输入排序值",
      rules: [{ required: false }],
      visible: false,
    },
    {
      valueType: "string",
      inputType: "date-picker",
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      disabled: true,
      visible: false,
      rules: [{ required: false }],
    },
    {
      valueType: "string",
      inputType: "date-picker",
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      disabled: true,
      visible: false,
      rules: [{ required: false }],
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 400,
      render: (_: any, record: DeviceInfoFeild) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            icon={<FolderAddOutlined />}
            onClick={() => tableAction.detail?.(record)}
          >
            功能数据
          </Button>
          <Button
            type="link"
            size="small"
            icon={<AreaChartOutlined />}
            onClick={() => tableAction.custom?.(record)}
          >
            模板
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => tableAction.edit?.(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除此设备？"
            description="删除设备将无法恢复"
            onConfirm={() => tableAction.delete?.([record.deviceId])}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
};
